package com.whitealbum2z.whitealbum2zaicodezero.aop;


import com.whitealbum2z.whitealbum2zaicodezero.annotation.AuthCheck;
import com.whitealbum2z.whitealbum2zaicodezero.exception.BusinessException;
import com.whitealbum2z.whitealbum2zaicodezero.exception.ErrorCode;
import com.whitealbum2z.whitealbum2zaicodezero.model.entity.User;
import com.whitealbum2z.whitealbum2zaicodezero.model.enums.UserRoleEnum;
import com.whitealbum2z.whitealbum2zaicodezero.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;

@Aspect
@Component
public class AuthInterceptor {


    @Resource
    private UserService userService;

    /**
     * 执行拦截
     *
     * @param joinPoint 切入点
     * @param authCheck 权限校验注解
     * @return
     * @throws Throwable
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        //注意，只适用当前项目  因为只分 管理员 和 普通人

        //接口需要的权限
        String mustRole = authCheck.mustRole();

        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        //拿到httpServletRequest
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        //获取当前登录的用户信息
        User loginUser = userService.getLoginUser(request);

        //对接口权限的类型 转换以下
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);

        // 这个接口不需要权限，直接放行
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }

        //以下是需要权限的接口校验

        //当前用户的权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());

        if(userRoleEnum == null){
            //用户没有权限，直接拒绝
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        //接口需要管理员权限， 但是用户没有权限
        if(UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        //通过权限校验
        return joinPoint.proceed();

    }

}
